package qy.jalgotrade.strategy.position;

import qy.jalgotrade.broker.Order;
import qy.jalgotrade.strategy.BaseStrategy;

/**
 * This class is reponsible for order management in long positions.
 * 
 * @author qy
 *
 */
public class LongPosition extends Position {

	public LongPosition(BaseStrategy strategy, String instrument, double stopPrice, double limitPrice, double quantity,
	        boolean goodTillCanceled, boolean allOrNone) throws Exception {

		super();

		Order entryOrder = null;
		if (Double.isNaN(limitPrice) && Double.isNaN(stopPrice)) {
			entryOrder = strategy.getBroker().createMarketOrder(Order.Action.BUY, instrument, quantity, false);
		} else if (!Double.isNaN(limitPrice) && Double.isNaN(stopPrice)) {
			entryOrder = strategy.getBroker().createLimitOrder(Order.Action.BUY, instrument, limitPrice, quantity);
		} else if (Double.isNaN(limitPrice) && !Double.isNaN(stopPrice)) {
			entryOrder = strategy.getBroker().createStopOrder(Order.Action.BUY, instrument, stopPrice, quantity);
		} else if (!Double.isNaN(limitPrice) && !Double.isNaN(stopPrice)) {
			entryOrder = strategy.getBroker().createStopLimitOrder(Order.Action.BUY, instrument, stopPrice, limitPrice,
			        quantity);
		} else {
			assert false;
		}

		_init(strategy, entryOrder, goodTillCanceled, allOrNone);
	}

	/*
	 * (non-Javadoc)
	 * @see qy.jalgotrade.strategy.position.Position#buildExitOrder(double, double)
	 */
	@Override
	public Order buildExitOrder(double stopPrice, double limitPrice) throws Exception {

		Order ret = null;
		double quantity = getShares();
		assert quantity > 0;
		if (Double.isNaN(limitPrice) && Double.isNaN(stopPrice)) {
			ret = getStrategy().getBroker().createMarketOrder(Order.Action.SELL, getInstrument(), quantity, false);
		} else if (!Double.isNaN(limitPrice) && Double.isNaN(stopPrice)) {
			ret = getStrategy().getBroker().createLimitOrder(Order.Action.SELL, getInstrument(), limitPrice, quantity);
		} else if (Double.isNaN(limitPrice) && !Double.isNaN(stopPrice)) {
			ret = getStrategy().getBroker().createStopOrder(Order.Action.SELL, getInstrument(), stopPrice, quantity);
		} else if (!Double.isNaN(limitPrice) && !Double.isNaN(stopPrice)) {
			ret = getStrategy().getBroker().createStopLimitOrder(Order.Action.SELL, getInstrument(), stopPrice,
			        limitPrice, quantity);
		} else {
			assert false;
		}

		return ret;
	}
}
